﻿using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Data.Common;
using System.Threading.Tasks;

namespace WMS.Data.Base
{
    public class BaseRepository
    {
        private static DbConnection connection = null;
        private static readonly object mutex = new object();

        public string ConnectionString { get; protected set; }

        protected DbConnection DbContext
        {
            get
            {
                var dbstate = connection?.State ?? ConnectionState.Closed;
                if (dbstate != ConnectionState.Open)
                {
                    lock (mutex)
                    {
                        if (connection != null)
                        {
                            CloseDbAsync(connection);
                        }
                        connection = GetMySqlConnection();
                    }
                }
                return connection;
            }
        }

        private async void CloseDbAsync(DbConnection connection)
        {
            try
            {
                await Task.Delay(TimeSpan.FromMinutes(5));
                switch (connection.State)
                {
                    case ConnectionState.Executing:
                    case ConnectionState.Fetching:
                    case ConnectionState.Open:
                        {
                            await connection.CloseAsync();
                            break;
                        }
                }
                await connection.DisposeAsync();
            }
            catch
            {
            }
        }

        private MySqlConnection GetMySqlConnection(
            bool convertZeroDatetime = false,
            bool allowZeroDatetime = false
        )
        {
            MySqlConnection ret;
            var csb = new MySqlConnectionStringBuilder(ConnectionString)
            {
                AllowZeroDateTime = allowZeroDatetime,
                ConvertZeroDateTime = convertZeroDatetime
            };

            ret = new MySqlConnection(csb.ConnectionString);
            return ret;
        }

    }
}
